<?php
namespace system\platform\controller;

class Database{

    private $path_backup = _APP_PATH_ . '/data/backup/';
   
    // 备份文件列表
    function index(){
        //检查目录是否存在
        if(file_exists( $this->path_backup )==false){
            mkdir($this->path_backup , 0755, true );
        }

        $dir_list = scandir( $this->path_backup );
        // 比对目录
        foreach($dir_list as $k => $v){
            if( $v=='.' || $v=='..' 
                || is_dir( $this->path_backup . $v)==true ){
                unset($dir_list[$k]);
            }
        }
        require view('default/database/index.tpl.php');
    } 

    // 建立备份
    function backup(){
        $arr_return=[ 'code'=>-1, 'msg'=>'缺少重要信息' ];

        $str_sql  = "-- -----------------------------\n";
        $str_sql .= "-- PHPwork MySQL Data Transfer \n";
        $str_sql .= "-- \n";
        $str_sql .= "-- Source Host     : " . $GLOBALS['config']['database']['hostname'] . "\n";
        $str_sql .= "-- Source Port     : " . $GLOBALS['config']['database']['hostport'] . "\n";
        $str_sql .= "-- Source Database : " . $GLOBALS['config']['database']['database'] . "\n";
        $str_sql .= "-- \n";
        $str_sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
        $str_sql .= "-- -----------------------------\n\n";
        $str_sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";


        //查询所有的数据表名
        $sql = 'SHOW TABLE STATUS';
        $rs_db = $GLOBALS['db']->query($sql)->fetchAll();
        foreach( $rs_db as $row_table){
            $sql = 'SHOW CREATE TABLE ' . $row_table['Name'] ;
            $rs_table = $GLOBALS['db']->query($sql)->fetch();
            //print_r($rs_table['Create Table']);
            $str_sql .= "DROP TABLE IF EXISTS `{$row_table['Name']}`;\n";
            $str_sql .= $rs_table['Create Table'] . ";\n\n";

            //备份数据记录
            $rs = $GLOBALS['db']->query("SELECT * FROM `{$row_table['Name']}` ")->fetchall(\PDO::FETCH_ASSOC);
            foreach ($rs as $row) {
				$table_column=[];	// 字段名
				$table_data=[];		// 字段对应的数据
				foreach($row  as $k=>$v){
					$table_column[] = "`$k`" ;
					if( $v!==NULL ){
						$table_data[$k] = addslashes($row[$k]) ;
						$table_data[$k] = str_replace(array("\r", "\n"), array('\\r', '\\n'),$table_data[$k]) ;
						$table_data[$k] = "'" . $table_data[$k] . "'";
					}else{
						$table_data[$k] = 'NULL';
					}
				}
                $str_sql .= "INSERT INTO `{$row_table['Name']}` (";
				$str_sql .= implode(", ", $table_column) ;
				$str_sql .= ") VALUES (" ;
				$str_sql .= implode(", ", $table_data) ;
				$str_sql .=	");\n";
			}
            $str_sql .= "\n\n";
        }

        //print_r($rs_table);
        file_put_contents( $this->path_backup . 'backup_' . date('YmdHis') .  mt_rand(10,99) . '.sql', $str_sql);

        $arr_return['code'] = 1;
        echo json_encode($arr_return);
    }

    // 还原备份
    function restore(){
        $arr_return=[ 'code'=>-1, 'message'=>'缺少重要信息' ];

        $f_name = $this->path_backup . $_GET['f'];
        $sql = file_get_contents($f_name);
        $GLOBALS['db']->query( $sql );

        $arr_return['code'] = 200;  // 成功
        echo json_encode($arr_return);
    }

    // 删除备份
    function delete(){
        $f_name = $this->path_backup . $_GET['f'];
        if( file_exists(  $f_name ) ){
            if( unlink( $f_name ) ){
                message('文件删除成功',url('platform/database/index') );
            }
        }
        message('文件删除失败', url('platform/database/index') );
    }

    // 下载备份
    function down(){
        $f_name = $this->path_backup . $_GET['f'];
        if (file_exists($f_name)) {
            ob_end_clean();

            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($f_name).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($f_name));
        
            readfile($f_name);
        } else {
            message('备份文件下载失败', url('platform/database/index') );
        }

    }

}